package com.allwees.bs.c.common.auth.oauth.google;

import com.alibaba.fastjson.JSONObject;
import com.allwees.bs.c.common.auth.AuthHandler;
import com.allwees.bs.c.common.auth.AuthResult;
import com.allwees.bs.c.common.auth.model.OAuthUserInfo;
import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.req.ThirdPartLoginReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(false)
public abstract class BaseGoogleAuthHandler extends AuthHandler {
	@Override
	public AuthResult auth(ThirdPartLoginReq req) {
		JSONObject json = fetchUserInfo(req);
		String id = json.getString("id");
		String email = json.getString("email");
		String firstName = json.getString("given_name");
		String lastName = json.getString("family_name");
		String avatarUrl = json.getString("picture");
		OAuthUserInfo userInfo = new OAuthUserInfo(req.getSourceType(), getAuthType(), req.getShareCode(), id, email, firstName, lastName, avatarUrl);
		//首选email
		UserEntity user = null;
		boolean save = false;
		if(StringUtils.isNotBlank(email)){
			user = userDao.findByEmail(email);
		}
		if(user == null){
			user = userDao.findByGoogleId(id);
		} else {
			if(StringUtils.isBlank(user.getGoogleId())){
				user.setGoogleId(id);
				save = true;
			}
			save = save || super.completeUserInfo(user, email, firstName, lastName, avatarUrl);
		}
		return auth(user, userInfo, save);
	}

	protected abstract JSONObject fetchUserInfo(ThirdPartLoginReq req);
}
